package cn.itzzx.lagou.controller;

import cn.itzzx.lagou.service.CodeService;
import cn.itzzx.lagou.service.MailFeignClientService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;

/**
 * TODO
 *
 * @author Martin
 * @since 1.0
 */
@RestController
@RequestMapping("code")
public class CodeController {
    private static Random random = new Random();

    @Resource
    private CodeService codeService;

    @Resource
    private MailFeignClientService mailFeignClientService;
    /**
     * 生成验证码
     */
    @PostMapping("create/{email}")
    public boolean create(@PathVariable String email) {
        //生成6位数密码
        int num = random.nextInt(900000) + 100000;
        String code = String.valueOf(num);
        //保存到数据库

        int result = codeService.insertCode(code,email);

        //调用邮件服务 发送邮箱
        if(result > 0){
            mailFeignClientService.send(email,code);
            return true;
        }
        return false;
    }

    /**
     * 校验验证码
     */
    @PostMapping("validate/{email}/{code}")
    public Integer validate(@PathVariable("email") String email,
                            @PathVariable("code") String code){
        return codeService.validateCode(email,code);
    }

}
